<?php

require_once('Zend/Db/Table/Row/Abstract.php');
require_once('Zend/Db/Table/Abstract.php');
require_once('Zend/Db/Table.php');
require_once('Zend/Db/Expr.php');

class Core_OAuth_Token
	extends Zend_Db_Table_Row_Abstract
{
	
	/**
	 * Enumerable property: This is a request token.
	 * 
	 * @var string
	 */
	const REQUEST = 'request';
	
	/**
	 * Enumerable property: This is an access token.
	 * 
	 * @var string
	 */
	const ACCESS = 'access';
	
	/**
	 * Private static reference to the table.
	 * 
     * @return Zend_Db_Table
	 */
	private static $table;
	
    /**
     * Name of the class of the Zend_Db_Table_Abstract object.
     *
     * @var string
     */
    protected $_tableClass = 'Zend_Db_Table';

    /**
     * Select access method, for slightly more complex queries.
     *
     * @return Zend_Db_Table_Select
     */
    public static function getTableInstance()
    {
    	if ( empty(Core_OAuth_Token::$table ) )
    	{
    		Core_OAuth_Token::$table = new Zend_Db_Table('oauth_token');
    		Core_OAuth_Token::$table->setRowClass('Core_OAuth_Token');
    	}
    	
    	return Core_OAuth_Token::$table;
    }
    
    /**
     * Factory Method. Spits out an object that's tied to the database.
     *
     * @return Core_OAuth_Token
     */
    public static function factory( $id_or_token  = null)
    {
    	$table = Core_OAuth_Token::getTableInstance();
    	$row = null;
    	
    	if ( is_null($id_or_token))
    	{
	    	// Create new
    		$row = $table->createRow(array(), Zend_Db_Table_Abstract::DEFAULT_DB);
    	}
    	else if ( is_string($id_or_token) )
    	{
    		// Find by consumer key.
    		$row = $table->fetchRow( $table->select()->where('token=?',$id_or_token));
    	}
    	else if ( is_int($id_or_token) )
    	{
    		// Find by ID.
    		$row = $table->fetchRow( $table->select()->where('oauthTokenId=?',$id_or_token));
    	}
    	
    	return $row;
    }
    
	
	/**
	 * @inheritDoc
	 */
    protected function _doInsert()
    {
    	$this->created = new Zend_Db_Expr('NOW()');
    	$this->updated = new Zend_Db_Expr('NOW()');
    	
    	parent::_doInsert();
    }
    
	/**
	 * @inheritDoc
	 */
    protected function _doUpdate()
    {
    	$this->updated = new Zend_Db_Expr('NOW()');
    	
    	parent::_doUpdate();
    }
}